﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using System.Linq;

[AddComponentMenu("UI/Effects/Gradient")]
public class Gradient : BaseMeshEffect
{
    [SerializeField]
    private Color32 topColor = Color.white;
    [SerializeField]
    private Color32 bottomColor = Color.black;

    //public override void ModifyVertices(List<UIVertex> vertexList)
    //{
    //    if (!IsActive())
    //    {
    //        return;
    //    }

    //    int count = vertexList.Count;
    //    if (count > 0)
    //    {
    //        float bottomY = vertexList[0].position.y;
    //        float topY = vertexList[0].position.y;

    //        for (int i = 1; i < count; i++)
    //        {
    //            float y = vertexList[i].position.y;
    //            if (y > topY)
    //            {
    //                topY = y;
    //            }
    //            else if (y < bottomY)
    //            {
    //                bottomY = y;
    //            }
    //        }

    //        float uiElementHeight = topY - bottomY;

    //        for (int i = 0; i < count; i++)
    //        {
    //            UIVertex uiVertex = vertexList[i];
    //            uiVertex.color = Color32.Lerp(bottomColor, topColor, (uiVertex.position.y - bottomY) / uiElementHeight);
    //            vertexList[i] = uiVertex;
    //        }
    //    }
    //}

    public override void ModifyMesh(VertexHelper vh)
    {
        if (!IsActive())
        {
            return;
        }

        int count = vh.currentVertCount;
        if (count > 0)
        {
            UIVertex temp = new UIVertex();
            vh.PopulateUIVertex(ref temp, 0);
            float bottomY = temp.position.y;
            float topY = temp.position.y;

            for (int i = 1; i < count; i++)
            {
                vh.PopulateUIVertex(ref temp, i);
                float y = temp.position.y;
                if (y > topY)
                {
                    topY = y;
                }
                else if (y < bottomY)
                {
                    bottomY = y;
                }
            }

            float uiElementHeight = topY - bottomY;

            for (int i = 0; i < count; i++)
            {
                vh.PopulateUIVertex(ref temp, i);
                temp.color = Color32.Lerp(bottomColor, topColor, (temp.position.y - bottomY) / uiElementHeight);
                vh.SetUIVertex(temp, i);
            }
        }
    }
}
